﻿using System.Windows.Forms;
using RSuite.Services;

namespace RSuite.R4.Services
{
    public class MainLocalService: LocalServiceBase
    {
        private Package package;

        protected override object Process(string method, dynamic parameters, string taskId)
        {
            switch (method)
            {
                case "new":
                    this.package = new Package();
                    return this.package;
                case "open":
                    return this.Open();
                case "save":
                    return this.Save(parameters);
                case "change-folder":
                    return base.Async(taskId, delegate()
                    {
                        this.package.Input = parameters;
                        return this.package.CacheItems();
                    });
                case "search":
                    return this.package.Search(parameters["input"], parameters["limit"]);
                case "pack":
                    this.package.Update(parameters);
                    return this.package.Pack();
                default:
                    return null;
            }
        }

        private Package Open()
        {
            var dialog = new OpenFileDialog();

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return null;
            }

            this.package = Package.FromFile(dialog.FileName);

            return this.package;
        }

        private string Save(object data)
        {
            if (string.IsNullOrEmpty(this.package.Filename))
            {
                var dialog = new SaveFileDialog();
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return string.Empty;
                }

                this.package.Update(data);
                this.package.Save(dialog.FileName);
            }
            else
            {
                this.package.Update(data);
                this.package.Save();
            }

            return this.package.Filename;
        }
    }
}